package com.scnlf.scnlf.portal.core.common.lock;

import com.scnlf.scnlf.portal.core.common.enums.ExpressionTypeEnum;
import com.scnlf.scnlf.portal.core.common.utils.SpelExpressionUtils;
import io.micrometer.core.instrument.util.StringUtils;

public class DistributedLockUtils {

    public static String getLockKey(DistributedLock distributedLock, Object[] args){
        ExpressionTypeEnum expressionType = distributedLock.expressionType();
        String expression = distributedLock.expression();
        String lockPrefix;
        if(expressionType == ExpressionTypeEnum.CONSTANT){
            lockPrefix = expression;
        } else {
            int index = distributedLock.expressionParamIndex();
            if(index >= args.length){
                throw new RuntimeException("distributed lock express index config error");
            }

            lockPrefix = SpelExpressionUtils.getStringValue(args[index], expression);
            if(StringUtils.isBlank(lockPrefix)){
                throw new RuntimeException("distributed lock express parse lock prefix error");
            }
        }
        String defaultPrefix = distributedLock.defaultPrefix();
        String lockKey = String.format(defaultPrefix + lockPrefix);
        return lockKey;
    }


}
